/**
 * Created by xc on 17/05/26.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');
var async  = require( 'async'); // 同步控制


// Schema 结构
var ItbCartModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '项目id',
  //`base_id` bigint(20) DEFAULT NULL COMMENT '主商品项目id(例如:配件从属于印品商品)',
  //`user_id` bigint(20) NOT NULL COMMENT '用户id',
  //`type` bigint(20) NOT NULL COMMENT '大分类',
  //`item_id` bigint(20) NOT NULL COMMENT '商品id(购买模版时为模版id)',
  //`user_doc_id` bigint(20) DEFAULT NULL COMMENT '用户作品文档id',
  //`pp_id` bigint(20) DEFAULT NULL COMMENT '套餐id',
  //`unit` varchar(20) NOT NULL DEFAULT '' COMMENT '单位',
  //`qty` bigint(20) NOT NULL COMMENT '数量',
  //`selected` int(2) NOT NULL DEFAULT '0' COMMENT '是否选中',
  //`fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '商品总金额(单位分)',
  //`product_fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '子项：生产费(单位分)',
  //`design_fee` bigint(12) NOT NULL DEFAULT '0' COMMENT '子项：设计费(单位分)',
  //`state` int(3) DEFAULT NULL COMMENT '状态：待定',
  //`desc` text COMMENT '备注',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0' COMMENT '删除flg',

};
ItbCartModel.prototype = new ItbBaseModel();

// 取得表名
ItbCartModel.prototype.getTableName = function(){
    return 'itb_cart';
};

// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbCartModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'id='+this.id;
};

/**
 * 获取用户购物车商品总数
 * @param userId
 * @param callback
 */
ItbCartModel.prototype.getGoodsCntByUser = function(userId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.getGoodsListByUser Err:'+err);
            return callback(err, null);
        }
        // Use the connection
        var sql = ' SELECT COUNT(t.id) AS totalCnt, '+
            ' IFNULL(SUM(CASE WHEN t.selected>0 THEN 1 ELSE 0 END),0) AS selCnt '+
            ' FROM itb_cart t '+
            ' WHERE t.user_id='+userId+
            ' AND t.del_flg = 0 AND t.base_id IS NULL ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(result && result.length>0) {
                return callback(error, result[0]);
            } else {
                return callback(error, null);
            }
        });
    });
};

/**
 * 获取某商品的配件
 * @param baseId
 * @param callback
 */
ItbCartModel.prototype.getAssyByBaseId = function(userId, baseId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.getAssyByBaseId Err:'+err);
            return callback(err, null);
        }

        // Use the connection
        var sql = ' SELECT t.* '+
            ' FROM itb_cart t '+
            ' WHERE t.del_flg=0 AND t.base_id='+baseId;
        if(userId>0){
            sql += ' AND t.user_id='+userId;
        }
        sql += ' ORDER BY t.id ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            return callback(error, result);
        });
    });
};

/**
 * 移除购物车商品
 * @param userId
 * @param arrIds: id数组
 * @param callback
 */
ItbCartModel.prototype.removeGoods = function(userId, arrIds, callback){
    var THIS = this;
    var tableName = this.getTableName();

    var ids = (arrIds||[]).join(',');

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.removeGoods Err:'+err);
            return callback(err, null);
        }

        // Use the connection
        var sql = ' UPDATE itb_cart t '+
            ' SET t.del_flg=1, t.update_time=sysdate(), update_by= '+userId+
            ' WHERE t.del_flg=0 '+
            ' AND t.user_id='+userId+
            ' AND (t.id IN ('+ids+') OR t.base_id IN ('+ids+')) ';

        console.log(sql);
        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

/**
 * 移除购物车选中商品
 * @param userId
 * @param callback
 */
ItbCartModel.prototype.removeSelectedGoods = function(userId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.removeSelectedGoods Err:'+err);
            return callback(err, null);
        }

        // Use the connection
        var sql = ' UPDATE itb_cart t '+
            ' SET t.del_flg=1, t.update_time=sysdate(), update_by= '+userId+
            ' WHERE t.del_flg=0 AND t.selected=1 '+
            ' AND t.user_id='+userId;

        console.log(sql);
        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

/**
 * 移除指定商品的配件
 * @param userId
 * @param arrIds: id数组
 * @param callback
 */
ItbCartModel.prototype.removeAssy = function(userId, arrIds, callback){
    var THIS = this;
    var tableName = this.getTableName();

    var ids = (arrIds||[]).join(',');

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.removeAssy Err:'+err);
            return callback(err, null);
        }

        // Use the connection
        var sql = ' UPDATE itb_cart t '+
            ' SET t.del_flg=1, t.update_time=sysdate(), update_by= '+userId+
            ' WHERE t.del_flg=0 '+
            ' AND t.user_id='+userId+
            ' AND t.base_id IN ('+ids+')';

        console.log(sql);
        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

/**
 * 设置购物车商品选中状态
 * @param userId
 * @param arrIds: 组合商品id数组(为空表示操作所有商品)
 * @param selected: 0不选中,1选中
 * @param callback
 */
ItbCartModel.prototype.setGoodsSelected = function(userId, arrIds, selected, callback){
    var THIS = this;
    var tableName = this.getTableName();

    var ids = (arrIds||[]).join(',');

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.setGoodsSelected Err:'+err);
            return callback(err, null);
        }

        // Use the connection
        var sql = ' UPDATE itb_cart t '+
            ' SET t.selected='+selected+
            '    ,t.update_time=sysdate(), update_by= '+userId+
            ' WHERE t.del_flg=0 '+
            ' AND t.user_id='+userId;
        if(ids && ids.length>0) {
            sql += ' AND (t.id IN ('+ids+') OR t.base_id IN ('+ids+')) ';
        }

        console.log(sql);
        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            if(error) {
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

/**
 * 获取购物车商品信息
 * @param userId
 * @param pageNum
 * @param pageSize
 * @param callback(按组合商品id分组)
 */
ItbCartModel.prototype.getGoodsInfoByUser = function(userId, pageNum, pageSize, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.getGoodsInfoByUser Err:'+err);
            return callback(err, null);
        }

        // Use the connection
        var sql = ' SELECT x.*, '+
            '   t2.id AS assy_id, t2.item_id AS assy_item_id, t2.unit AS assy_unit, t2.qty AS assy_qty, '+
            '   t2.fee AS assy_fee, t2.product_fee AS assy_product_fee, t2.design_fee AS assy_design_fee, '+
            '   t2.pp_id AS assy_pp_id, pp2.pp_name AS assy_pp_name, pp2.desc AS assy_pp_desc' +
            ', pp2.pricing as assy_pp_pricing '+ // add 2017-08-25 by wangjun 增加配件计价方式

            ' FROM ('+
            '  SELECT t.*, pp.pp_name, pp.desc AS pp_desc, func_parse_string_array(it.thumbs,0) AS thumb, it.item_name, up.thumb AS user_doc_thumb' +
            ', pp.pricing as pp_pricing'+  // add 2017-08-25 by wangjun 增加商品计价方式
            '  FROM itb_cart t '+
            '  LEFT JOIN itb_items it ON it.del_flg=0 AND it.item_id=t.item_id '+
            '  LEFT JOIN tg_user_page up ON up.del_flg=0 AND up.page_index=0 AND up.doc_id=t.user_doc_id '+
            '  LEFT JOIN itb_print_param pp ON pp.del_flg=0 AND pp.pp_id=t.pp_id '+
            '  WHERE t.del_flg=0 AND t.base_id IS NULL AND t.user_id= '+userId;
        if(THIS.selected==1) {
            // 只获取选中商品
            sql += ' AND t.selected=1 ';
        }
        if(typeof pageNum!='undefined' && pageNum != null && typeof pageSize!='undefined' && pageSize != null){
            sql += " limit " + (Number(pageNum||'0')*Number(pageSize||'0')) + "," + Number(pageSize||'0');
        }
        sql += ' ) x '+

            ' LEFT JOIN itb_cart t2 ON t2.del_flg=0 AND t2.base_id=x.id '+// 配件
            ' LEFT JOIN itb_print_param pp2 ON pp2.del_flg=0 AND pp2.pp_id=t2.pp_id '+
            ' ORDER BY x.id DESC, x.create_time DESC, t2.create_time DESC ';

        console.log(sql);
        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            var retInfo=[];
            if(result) {
                var tmpItem=null;
                var tmpAssy=new Array();

                for(var i=0; i<result.length; i++) {
                    if(i==0) {
                        tmpItem = result[0];
                        tmpItem.totalFee = result[0].product_fee;// 除去设计费
                    }

                    if(result[i].id != tmpItem.id) {// id变更
                        retInfo.push({
                            id: tmpItem.id,
                            itemId: tmpItem.item_id,
                            userDocId: tmpItem.user_doc_id,
                            thumb: tmpItem.user_doc_thumb||tmpItem.thumb,
                            title: tmpItem.item_name,
                            itemParam: {
                                ppId: tmpItem.pp_id,
                                title: tmpItem.pp_name,
                                desc: tmpItem.pp_desc,
                                pricing : tmpItem.pp_pricing
                            },
                            itemCnt: {
                                price: tmpItem.product_fee,
                                show: tmpItem.qty,
                                unit: tmpItem.unit
                            },
                            assyList: tmpAssy,
                            selected: tmpItem.selected,
                            designFee: tmpItem.design_fee,
                            totalFee: tmpItem.totalFee,
                        });

                        tmpItem = result[i];
                        tmpItem.totalFee = result[i].product_fee;
                        tmpAssy = new Array();
                    }

                    if(result[i].assy_id>0) {
                        tmpAssy.push({
                            id: result[i].assy_id,
                            itemId: result[i].assy_item_id,
                            assyParam: {
                                ppId: result[i].assy_pp_id,
                                title: result[i].assy_pp_name,
                                desc: result[i].assy_pp_desc,
                                pricing : result[i].assy_pp_pricing
                            },
                            assyCnt: {
                                price: result[i].assy_product_fee,// TODO
                                show: result[i].assy_qty,
                                unit: result[i].assy_unit
                            }
                        });
                        tmpItem.totalFee += result[i].assy_product_fee||0;
                    }

                    if(i==result.length-1) {// 最后一条
                        retInfo.push({
                            id: tmpItem.id,
                            itemId: tmpItem.item_id,
                            userDocId: tmpItem.user_doc_id,
                            thumb: tmpItem.user_doc_thumb||tmpItem.thumb,
                            title: tmpItem.item_name,
                            itemParam: {
                                ppId: tmpItem.pp_id,
                                title: tmpItem.pp_name,
                                desc: tmpItem.pp_desc,
                                pricing : tmpItem.pp_pricing
                            },
                            itemCnt: {
                                price: tmpItem.product_fee,
                                show: tmpItem.qty,
                                unit: tmpItem.unit
                            },
                            assyList: tmpAssy,
                            selected: tmpItem.selected,
                            designFee: tmpItem.design_fee,
                            totalFee: tmpItem.totalFee,
                        });
                    }
                }
            }

            callback(error, retInfo);
        });
    });
};

/**
 * 根据购物车的选中状态预先计算费用：制作费、设计费、优惠费、邮费、总费用、以及各商品的分开的费用
 * 返回值包括购物车选中商品的信息（按组合商品分组）
 * @param userId
 * @param couponId
 * @param callback
 */
ItbCartModel.prototype.procGetPrepayOrderInfo = function(userId, couponId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'CALL proc_calc_prepay_order_fee2('+userId+
            ','+couponId+// 优惠劵id（如果不存在，则传入0）
            ',@product_fee '+// 制作费用
            ',@design_fee '+// 设计费用
            ',@coupon_fee '+// 优惠（注意优惠费<=优惠劵费）
            ',@mail_fee '+// 邮费
            ',@total_fee '+// 总费用
            ',@used_addr_id '+// 计算使用的地址id（如果不存在，则返回0）
            ',@used_c_id '+// 计算使用的优惠劵id
            ');';
        /**
         * 注意：
         * 1、会做优惠劵的有效性检测，如果无效则coupon_fee返回0
         * 2、如果存在地址则返回邮费和地址id，否则返回0
         * 3、select返回值如下（条数>=1）：
         * (共同部分)
         * product_fee, 总制作费用
         * design_fee, 总设计费用
         * coupon_fee, 总优惠费用
         * mail_fee, 总邮费
         * total_fee, 总费用
         * used_addr_id, 计算使用的地址id
         * used_c_id, 计算使用的优惠劵id
         * (存在选中商品时返回以下字段)
         * platform_id, 印刷厂id
         * goods_id, 购物车的项目的id	(印品的cart的id，配件的cart的base id)
         * item_id, 商品id
         * user_doc_id, 商品的用户文档id
         * pp_id, 商品的印刷套餐id
         * unit, 商品的单位
         * qty, 商品的数量
         * item_fee, 商品的费用（＝制作费＋设计费＋邮费）
         * item_product_fee, 商品的制作费
         * item_design_fee, 商品的设计费
         * item_mail_fee 商品的邮费（1、配件的邮费算到商品上，2、同一个印刷厂的多个商品的邮费算到第一个商品上）
         */

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(result && result.length>0 && result[0] && result[0].length>0){
                var arrRecd = result[0];

                var retInfo=[];// 返回值

                var tmpItem=null;// 主商品
                var tmpAssy=new Array();// 配件

                for(var i=0; i<arrRecd.length; i++) {
                    if(arrRecd[0].item_id) {
                        if(i==0) {
                            tmpItem = arrRecd[0];
                        }

                        if(arrRecd[i].goods_id != tmpItem.goods_id) {
                            tmpItem.assyList = tmpAssy;
                            retInfo.push(tmpItem);

                            tmpItem = arrRecd[i];
                            tmpAssy = new Array();
                        }

                        if(Number(arrRecd[i].user_doc_id||'0')==0) {
                            tmpAssy.push(arrRecd[i]);
                        }

                        if(i==arrRecd.length-1) {// 最后一条
                            tmpItem.assyList = tmpAssy;
                            retInfo.push(tmpItem);
                        }
                    }
                }

                callback(error, retInfo);

            }else{
                callback(error, null);
            }
        });
    });
};

/**
 * 获取购物车商品信息(包括全部套餐/价格/尺寸)
 * @param userId
 * @param id
 * @param callback(按套餐分组)
 * {"success":1,"msg":"成功","data":{"cur":{"itemId":36,"ppId":1,"cnt":2,"unit":"盒"},"item":{"itemId":36,"designFee":0,"productFee":2000,"itemParams":[{"ppId":1,"title":"铜版纸 通用商务","desc":"157克铜版纸 双面彩色印刷 防水膜","pricing":10,"size":{"width":90,"height":54,"unit":"mm","desc":"横版"},"qty":[{"priceId":1,"price":2000,"minCnt":2,"maxCnt":2,"show":"2","unit":"盒"}]}]}}}
 */
ItbCartModel.prototype.getGoodsFullInfoById = function(userId, id, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.getGoodsFullInfoById Err:'+err);
            return callback(err, null);
        }

        // Use the connection
        var sql = ' SELECT x.*, up.thumb AS user_doc_thumb FROM '+
            ' (SELECT t.id, t.item_id, t.user_doc_id '+
            '       ,t.pp_id AS cur_pp_id, t.qty AS cur_qty, t.unit AS cur_unit, t.design_fee, t.product_fee '+
            '       ,func_parse_string_array(it.thumbs,0) AS thumb, it.type_id '+
            '       ,s.size_id, s.print_w, s.print_h, s.print_unit, s.desc AS size_desc '+
            '       ,pp.pp_id, pp.pp_name, pp.desc AS pp_desc, pp.pricing '+
            '       ,qp.price_id, qp.price, qp.unit, qp.min, qp.max, qp.show '+
            ' FROM itb_cart t '+
            '     ,itb_items it '+
            '     ,itb_print_rel pr '+
            '     ,itb_print_param pp '+
            '     ,itb_qty_price qp '+
            '     ,tg_size s '+
            ' WHERE t.del_flg=0 AND t.id='+id+' AND t.user_id='+userId+
            ' AND it.item_id=t.item_id '+
            ' AND pr.del_flg=0 AND pr.item_id=t.item_id '+
            ' AND pp.del_flg=0 AND pp.pp_id=pr.pp_id '+
            ' AND qp.del_flg=0 AND qp.pp_id=pp.pp_id '+
            ' AND s.del_flg=0 AND s.size_id=pp.size_id ) x '+
            ' LEFT JOIN tg_user_page up ON up.del_flg=0 AND up.page_index=0 AND up.doc_id=x.user_doc_id '+
            ' ORDER BY x.id, x.pp_id, x.min ';

        console.log(sql);
        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            var retInfo=null;

            // 将返回值按套餐分组
            if(result) {
                retInfo = {};
                var ppInfo=null;
                var arrQty=new Array();

                for(var i=0; i<result.length; i++) {
                    if(i==0) {
                        ppInfo = result[0];

                        retInfo.cur = {
                            itemId: ppInfo.item_id,
                            ppId: ppInfo.cur_pp_id,
                            cnt: ppInfo.cur_qty,
                            unit: ppInfo.cur_unit,
                        };
                        retInfo.item = {
                            itemId: ppInfo.item_id,
                            thumb: ppInfo.user_doc_thumb||ppInfo.thumb,
                            typeId: ppInfo.type_id,
                            designFee: ppInfo.design_fee,
                            productFee: ppInfo.product_fee,
                            itemParams: []
                        };
                    }

                    if(result[i].pp_id != ppInfo.pp_id) {// 套餐id变更
                        retInfo.item.itemParams.push({
                            ppId: ppInfo.pp_id,
                            title: ppInfo.pp_name,
                            desc: ppInfo.pp_desc,
                            pricing: ppInfo.pricing,
                            size: {// TODO
                                sizeId: ppInfo.size_id,
                                width: ppInfo.print_w,
                                height: ppInfo.print_h,
                                unit: ppInfo.print_unit,
                                desc: ppInfo.size_desc
                            },
                            qty: arrQty
                        });

                        ppInfo = result[i];
                        arrQty = new Array();
                    }

                    arrQty.push({
                        priceId: result[i].price_id,
                        price: result[i].price,
                        minCount: result[i].min,
                        maxCount: result[i].max,
                        show: result[i].show,
                        unit: result[i].unit,
                    });

                    if(i==result.length-1) {// 最后一条
                        retInfo.item.itemParams.push({
                            ppId: ppInfo.pp_id,
                            title: ppInfo.pp_name,
                            desc: ppInfo.pp_desc,
                            pricing: ppInfo.pricing,
                            size: {// TODO
                                sizeId: ppInfo.size_id,
                                width: ppInfo.print_w,
                                height: ppInfo.print_h,
                                unit: ppInfo.print_unit,
                                desc: ppInfo.size_desc
                            },
                            qty: arrQty
                        });
                    }
                }
            }

            callback(error, retInfo);
        });
    });
};
/**
 * 获取购物车商品信息(包括全部套餐/价格/尺寸)
 * @param itemId
 * @param callback(按套餐分组)
 */
ItbCartModel.prototype.getGoodsFullInfoByItemId = function(itemId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.getGoodsFullInfoByItemId Err:'+err);
            return callback(err, null);
        }

        // Use the connection
        var sql =
            ' SELECT it.item_id '+
            '       ,func_parse_string_array(it.thumbs,0) AS thumb, it.type_id '+
            '       ,s.size_id, s.print_w, s.print_h, s.print_unit, s.desc AS size_desc '+
            '       ,pp.pp_id, pp.pp_name, pp.desc AS pp_desc, pp.pricing '+
            '       ,qp.price_id, qp.price, qp.unit, qp.min, qp.max, qp.show '+
            ' FROM itb_items it '+
            '     ,itb_print_rel pr '+
            '     ,itb_print_param pp '+
            '     ,itb_qty_price qp '+
            '     ,tg_size s '+
            ' WHERE it.del_flg=0 AND it.item_id='+itemId+
            ' AND pr.del_flg=0 AND pr.item_id=it.item_id '+
            ' AND pp.del_flg=0 AND pp.pp_id=pr.pp_id '+
            ' AND qp.del_flg=0 AND qp.pp_id=pp.pp_id '+
            ' AND s.del_flg=0 AND s.size_id=pp.size_id '+
            ' ORDER BY it.item_id, pp.pp_id, qp.min ';

        console.log(sql);
        //var sqlValue = [THIS.update_by, THIS.doc_id];
        //var sql = mysql.format(sql, sqlValue);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            var retInfo=null;

            // 将返回值按套餐分组
            if(result) {
                retInfo = {};
                var ppInfo=null;
                var arrQty=new Array();

                for(var i=0; i<result.length; i++) {
                    if(i==0) {
                        ppInfo = result[0];

                        retInfo.item = {
                            itemId: ppInfo.item_id,
                            thumb: ppInfo.thumb,
                            typeId: ppInfo.type_id,
                            itemParams: []
                        };
                    }

                    if(result[i].pp_id != ppInfo.pp_id) {// 套餐id变更
                        retInfo.item.itemParams.push({
                            ppId: ppInfo.pp_id,
                            title: ppInfo.pp_name,
                            desc: ppInfo.pp_desc,
                            pricing: ppInfo.pricing,
                            size: {// TODO
                                sizeId: ppInfo.size_id,
                                width: ppInfo.print_w,
                                height: ppInfo.print_h,
                                unit: ppInfo.print_unit,
                                desc: ppInfo.size_desc
                            },
                            qty: arrQty
                        });

                        ppInfo = result[i];
                        arrQty = new Array();
                    }

                    arrQty.push({
                        priceId: result[i].price_id,
                        price: result[i].price,
                        minCount: result[i].min,
                        maxCount: result[i].max,
                        show: result[i].show,
                        unit: result[i].unit,
                    });

                    if(i==result.length-1) {// 最后一条
                        retInfo.item.itemParams.push({
                            ppId: ppInfo.pp_id,
                            title: ppInfo.pp_name,
                            desc: ppInfo.pp_desc,
                            pricing: ppInfo.pricing,
                            size: {// TODO
                                sizeId: ppInfo.size_id,
                                width: ppInfo.print_w,
                                height: ppInfo.print_h,
                                unit: ppInfo.print_unit,
                                desc: ppInfo.size_desc
                            },
                            qty: arrQty
                        });
                    }
                }
            }

            callback(error, retInfo);
        });
    });
};


/**
 * 获取组合商品相关fee信息
 * @param  userId
 * @param  goodsId
 * @param  callback:回调
 */
ItbCartModel.prototype.getGoodsFeeInfoById = function(userId, goodsId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.getGoodsFeeInfo Err:'+err);
            return callback(err, null);
        }
        // Use the connection
        var sql = ' select SUM(t.product_fee) AS total_product_fee, SUM(t.design_fee) AS total_design_fee '+
            ' ,SUM(t.fee) AS total_fee '+
            ' FROM itb_cart t '+
            ' WHERE t.del_flg=0 '+
            ' AND t.user_id='+userId+
            ' AND (t.id='+goodsId+' OR t.base_id='+goodsId+') ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            if(result && result.length>0) {
                return callback(error, result[0]);
            } else {
                return callback(error, null);
            }
        });
    });
};

/**
 * 获取购物车选中的商品相关fee信息
 * @param  userId
 * @param  goodsId
 * @param  callback:回调
 */
ItbCartModel.prototype.getSelectedGoodsFeeInfo = function(userId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbCartModel.getSelectedGoodsFeeInfo Err:'+err);
            return callback(err, null);
        }
        // Use the connection
        var sql = ' select SUM(t.product_fee) AS total_product_fee, SUM(t.design_fee) AS total_design_fee '+
            ' ,SUM(t.fee) AS total_fee '+
            ' FROM itb_cart t '+
            ' WHERE t.del_flg=0 AND t.selected=1 '+
            ' AND t.user_id='+userId;

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            if(result && result.length>0) {
                return callback(error, result[0]);
            } else {
                return callback(error, null);
            }
        });
    });
};

/**
 * 计算购物车中选中商品的各种费用
 * @param userId
 * @param couponId
 * @param callback
 */
ItbCartModel.prototype.procGetPrepayOrderFee = function(userId, couponId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'CALL proc_calc_prepay_order_fee('+userId+
            ','+couponId+// 优惠劵id（如果不存在，则传入0）
            ',@product_fee '+// 制作费用
            ',@design_fee '+// 设计费用
            ',@coupon_fee '+// 优惠（注意优惠费<=优惠劵费）
            ',@mail_fee '+// 邮费
            ',@total_fee '+// 总费用
            ',@used_addr_id '+// 计算使用的地址id（如果不存在，则返回0）
            ',@used_c_id '+// 计算使用的优惠劵id
            ');';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(result && result.length>0 && result[0] && result[0].length>0){
                callback(error, result[0][0]);
            }else{
                callback(error, null);
            }
        });
    });
};


/**
 * 根据购物车的选中状态预先计算费用：制作费、设计费、优惠费、邮费、总费用、以及各商品的分开的费用
 * 返回值包括购物车选中商品的信息（按组合商品分组）
 * @param userId
 * @param couponId
 * @param addressId
 * @param callback
 */
ItbCartModel.prototype.procGetPrepayOrderInfo3 = function(userId, couponId, addressId, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'CALL proc_calc_prepay_order_fee3('+userId+
            ','+couponId+// 优惠劵id（如果不存在，则传入0）
            ','+addressId+ // 预结算地址 id, (如果不存在, 则传入0)
            ',@product_fee '+// 制作费用
            ',@design_fee '+// 设计费用
            ',@coupon_fee '+// 优惠（注意优惠费<=优惠劵费）
            ',@mail_fee '+// 邮费
            ',@total_fee '+// 总费用
            ',@used_addr_id '+// 计算使用的地址id（如果不存在，则返回0）
            ',@used_c_id '+// 计算使用的优惠劵id
            ');';
        /**
         * 注意：
         * 1、会做优惠劵的有效性检测，如果无效则coupon_fee返回0
         * 2、如果存在地址则返回邮费和地址id，否则返回0
         * 3、select返回值如下（条数>=1）：
         * (共同部分)
         * product_fee, 总制作费用
         * design_fee, 总设计费用
         * coupon_fee, 总优惠费用
         * mail_fee, 总邮费
         * total_fee, 总费用
         * used_addr_id, 计算使用的地址id
         * used_c_id, 计算使用的优惠劵id
         * weight, 总重量
         * (存在选中商品时返回以下字段)
         * platform_id, 印刷厂id
         * goods_id, 购物车的项目的id	(印品的cart的id，配件的cart的base id)
         * item_id, 商品id
         * user_doc_id, 商品的用户文档id
         * pp_id, 商品的印刷套餐id
         * unit, 商品的单位
         * qty, 商品的数量
         * item_fee, 商品的费用（＝制作费＋设计费＋邮费）
         * item_product_fee, 商品的制作费
         * item_design_fee, 商品的设计费
         * item_mail_fee 商品的邮费（1、配件的邮费算到商品上，2、同一个印刷厂的多个商品的邮费算到第一个商品上）
         */

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(result && result.length>0 && result[0] && result[0].length>0){
                var arrRecd = result[0];

                var retInfo=[];// 返回值

                var tmpItem=null;// 主商品
                var tmpAssy=new Array();// 配件

                for(var i=0; i<arrRecd.length; i++) {
                    if(arrRecd[0].item_id) {
                        if(i==0) {
                            tmpItem = arrRecd[0];
                        }

                        if(arrRecd[i].goods_id != tmpItem.goods_id) {
                            tmpItem.assyList = tmpAssy;
                            retInfo.push(tmpItem);

                            tmpItem = arrRecd[i];
                            tmpAssy = new Array();
                        }

                        if(Number(arrRecd[i].user_doc_id||'0')==0) {
                            tmpAssy.push(arrRecd[i]);
                        }

                        if(i==arrRecd.length-1) {// 最后一条
                            tmpItem.assyList = tmpAssy;
                            retInfo.push(tmpItem);
                        }
                    }
                }

                callback(error, retInfo);

            }else{
                callback(error, null);
            }
        });
    });
};

// 导出
module.exports = ItbCartModel;